import logging
import os

from tool.utils import write_as_excel, get_date, clock
from tool.repo_info import get_org_repo_url_list
from tool.utils_config import get_file_check_list_from_config
from tool.utils_net import is_file_existence_in_remote

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

logging.basicConfig(filename=BASE_DIR + '/check.log',
                    level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# logging.disable(logging.DEBUG)


@clock
def audit_files_existence_in_remote_main_directory(organization, output_file_name=None, file_list_need_to_check=None,
                                                   repo_filter=None):
    if not output_file_name:
        output_file_name = get_date() + '_' + organization + '组织_仓库合规检测报告.xlsx'
    if not file_list_need_to_check:
        file_list_need_to_check = get_file_check_list_from_config()
    report_info_list = []
    for file_name in file_list_need_to_check:
        print(f'当前判断{organization}组织中，合规文件{file_name}的存在')
        report_info_list.extend(audit_file_existence_for_org(organization, file_name, repo_filter=repo_filter))
    columns_order = ['仓库链接', '合规问题']
    write_as_excel(output_file_name, report_info_list, columns_order)
    print('结果报告：' + os.path.join(BASE_DIR, output_file_name))


def audit_file_existence_for_org(organization, file_need_to_check, repo_filter=None):
    fail_test_repo_url_list = []
    repo_url_list = list(filter(repo_filter, get_org_repo_url_list(organization)))
    print(f'组织{organization}总共{len(repo_url_list)}个仓')
    for i, repo_url in enumerate(repo_url_list):
        print(f'正在审查第{i + 1}个仓，总共{len(repo_url_list)}个仓需要审查')
        url_to_test = repo_url + '/blob/master/' + file_need_to_check
        print(f'当前判断链接为:{url_to_test}')
        if not is_file_existence_in_remote(url_to_test):
            fail_test_repo_url_list.append({'仓库链接': url_to_test, '合规问题': '缺失' + file_need_to_check})
    print('找到不合规数目：' + str(len(fail_test_repo_url_list)))
    return fail_test_repo_url_list


def only_third_party_repo(url):
    return 'third_party' in url


if __name__ == '__main__':
    # 审计三方仓库是否存在配置文件config.toml中file_to_check列表所示文件项，并生成报告
    audit_files_existence_in_remote_main_directory('openharmony', repo_filter=only_third_party_repo)
